package org.thava.fortune.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
import java.util.Scanner;

import org.thava.fortune.FortuneAndroidActivity;
import org.thava.fortune.R;

import android.util.Log;

public class FortuneReader {
	FortuneAndroidActivity activity = null;
//	String[][] fdata = []
	public FortuneReader(FortuneAndroidActivity fortuneAndroidActivity) throws IOException{
		this.activity = fortuneAndroidActivity;
		Log.d("fortune", "INitalized");
		BufferedReader buff = new BufferedReader(new InputStreamReader(
				activity.getResources().openRawResource(R.raw.work)));
		String line = "";
		while((line=buff.readLine())!=null){
			
		}
	}
	
//	private String getAFortune(){
//		
//	}

	public String getaFortune(){
		Log.d("fortune", "Function called");
		String fortune = "";
		int total_fotunes=0;
		int fortune_number=0;
		Log.d("fortune", "initialized");
		Scanner sc = getScanner();
		
		while(sc.hasNext()){
			total_fotunes += 1;
			sc.next();
		}
		Log.d("fortune", "total fortunes: "+total_fotunes);
		Random r = new Random();
		fortune_number = r.nextInt(total_fotunes);
		Log.d("fortune", "i'm going to fetch fortunes: "+fortune_number);
		sc.close();
		sc = getScanner();
		while(sc.hasNext()){
			fortune_number -= 1;
			if(fortune_number < 0){
				fortune = sc.next();
				Log.d("fortune", "fetched fortune: "+fortune);
				break;
			}
			sc.next();
		}
		Log.d("fortune", "returning fortune: "+fortune);
		return fortune;
	}
	
	private Scanner getScanner(){
		Scanner sc = new Scanner(new InputStreamReader(
				activity.getResources().openRawResource(R.raw.work)));
		sc.useDelimiter("%");
		return sc;
	}
}
